<template>
  <div v-if="permissionsLists(19)">
    <page-header :title="$t('m.Menu_Vendor_Merchant')" :has-return="false">
      <el-button
        type="primary"
        @click="
          $router.push({ path: '/vender/shop/create' })
        "
        v-if="permissionsLists(20)"
      >
        {{ $t('m.create_store') }}
      </el-button>
    </page-header>
    <div class="container">
      <div class="list_div">
        <div class="page_list_div">
          <el-form class="page_list_top" label-position="right">
            <el-form-item :label="$t('m.search_') + ':'" class="page_list_top">
              <el-input
                :placeholder="
                  [
                    this.$t('m.MerchantID'),
                    this.$t('m.Shop_name'),
                    this.$t('m.Shop_Details_Contact'),
                    this.$t('m.Merchant_owner_account')
                  ].join(' / ')
                "
                prefix-icon="el-icon-search"
                clearable
                style="min-width:286px;"
                v-model="params.search"
              />
            </el-form-item>

            <el-form-item
              :label="$t('m.branch_Creationdate') + ':'"
              class="page_list_top"
            >
              <el-date-picker
                style="width:246px;"
                v-model="params.rangeTime"
                :picker-options="datePickerOptions"
                :default-value="timeDefaultShow"
                type="daterange"
                :default-time="['00:00:00', '23:59:59']"
                value-format="timestamp"
                range-separator="~"
                :start-placeholder="$t('m.start_date')"
                :end-placeholder="$t('m.end_date')"
              >
              </el-date-picker>
            </el-form-item>

            <el-form-item
              :label="$t('m.Merchant_type') + ':'"
              class="page_list_top"
            >
              <el-select
                v-model="params.industryId"
                :placeholder="$t('m.pleaseChoose')"
                ref="select1"
                @change="searchClick('', 1)"
              >
                <el-option
                  v-for="item in typeOption"
                  :key="item.id"
                  :label="
                    item.description
                      ? item.industryName + ' (' + item.description + ')'
                      : item.industryName
                  "
                  :value="item.id"
                >
                </el-option>
              </el-select>
            </el-form-item>

            <el-form-item :label="$t('m.status') + ':'" class="page_list_top">
              <el-select
                v-model="params.state"
                :placeholder="$t('m.pleaseChoose')"
                ref="select2"
                @change="searchClick('', 2)"
              >
                <el-option
                  v-for="item in stateOption"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item class="page_list_top page_list_search">
              <el-button
                class="search_button reset_button"
                @click="searchClick('')"
                >{{ $t('m.search_') }}</el-button
              >
            </el-form-item>
            <el-form-item class="page_list_top page_list_search">
              <el-button class="reset_button" @click="searchClick('1')">{{
                $t('m.refresh')
              }}</el-button>
            </el-form-item>
          </el-form>
        </div>
        <el-divider class="el_divider"></el-divider>
        <div class="el_table_div">
          <el-table :data="page.records">
            <el-table-column
              prop="branchCode"
              :label="$t('m.MerchantID')"
              min-width="150"
            >
            </el-table-column>
            <el-table-column
              prop="branchName"
              :label="$t('m.Shop_name')"
              min-width="150"
            >
            </el-table-column>
            <el-table-column
              prop="phone"
              :label="$t('m.Shop_Details_Contact')"
              min-width="150"
            >
              <template slot-scope="scope">
                <span>{{ scope.row.phone | phoneFormat(scope.row.code) }}</span>
              </template>
            </el-table-column>
            <el-table-column
              prop="branchAccount"
              :label="$t('m.Merchant_owner_account')"
              min-width="150"
            >
              <template slot-scope="scope">
                <div
                  v-if="
                    scope.row.branchAccount && scope.row.branchAccount.phone
                  "
                >
                  {{
                    scope.row.branchAccount.phone
                      | phoneFormat(scope.row.branchAccount.code)
                  }}
                </div>
                <div v-else>
                  {{
                    scope.row.branchAccount && scope.row.branchAccount.email
                      ? scope.row.branchAccount.email
                      : '--'
                  }}
                </div>
              </template>
            </el-table-column>
            <el-table-column
              prop="cabinetNumber"
              :label="$t('m.Number_of_station')"
              min-width="150"
            >
            </el-table-column>
            <el-table-column
              prop="frequency"
              :label="$t('m.Number_of_orders')"
              min-width="150"
            >
            </el-table-column>
            <el-table-column
              prop="ratio"
              :label="$t('m.Shop_Details_Profit_allocation')"
              min-width="150"
            >
              <template slot-scope="scope">
                <div>{{ scope.row.ratio }}%</div>
              </template>
            </el-table-column>
            <el-table-column
              prop="totalAmount"
              :label="$t('m.Agency_Gross_volume')"
              min-width="150"
            >
              <template slot-scope="scope">
                <div>{{ scope.row.totalAmount | amountFormat }}</div>
              </template>
            </el-table-column>
            <el-table-column
              prop="pendingAmount"
              :label="$t('m.Shop_Payable_Available')"
              min-width="150"
            >
              <template slot-scope="scope">
                <div>{{ scope.row.pendingAmount | amountFormat }}</div>
              </template>
            </el-table-column>
            <el-table-column
              prop="agentName"
              :label="$t('m.Account_affiliatedFranchisee')"
              min-width="150"
            >
              <template slot-scope="scope">
                <div>
                  {{
                    (scope.row.agentName
                      ? scope.row.agentName
                      : $t('m.Platform')) | strFormat
                  }}
                </div>
              </template>
            </el-table-column>
            <el-table-column
              prop="payState"
              :label="$t('m.status')"
              min-width="150"
            >
              <template slot-scope="scope">
                <div>{{ scope.row.state | stateFormat(stateOption) }}</div>
              </template>
            </el-table-column>
            <el-table-column
              prop="orderState"
              :label="$t('m.branch_Creationdate')"
              min-width="150"
            >
              <template slot-scope="scope">
                <div>{{ scope.row.createTime | dateformat }}</div>
              </template>
            </el-table-column>
            <el-table-column
              fixed="right"
              :label="$t('m.Users_Details_Operation')"
              min-width="104"
              v-if="isArrayEqual([20, 22, 23, 174, 175, 206], permissionsLists)"
            >
              <template slot-scope="scope">
                <el-dropdown placement="bottom">
                  <img
                    src="@/assets/imgs/ic_operation.svg"
                    alt=""
                    class="dropdown_img"
                  />
                  <el-dropdown-menu
                    slot="dropdown"
                    style="white-space: nowrap !important;"
                  >
                    <el-dropdown-item
                      @click.native="detailClick(scope.row.id)"
                      v-if="permissionsLists(22)"
                      >{{ $t('m.Details') }}</el-dropdown-item
                    >
                    <el-dropdown-item
                      @click.native="eidtShop(scope.row.id)"
                      v-if="permissionsLists(20)"
                      >{{ $t('m.branch_Edit') }}</el-dropdown-item
                    >
                    <el-dropdown-item
                      @click.native="dialogClick(scope.row)"
                      v-if="
                        (scope.row.state == 1 || scope.row.state == 2) &&
                          permissionsLists(23)
                      "
                      >{{
                        scope.row.state == 1
                          ? $t('m.branch_Terminate')
                          : $t('m.branch_resumePartnership')
                      }}</el-dropdown-item
                    >
                    <el-dropdown-item
                      @click.native="inviteStore(scope.row)"
                      v-if="permissionsLists(175)"
                      >{{
                        scope.row.uid
                          ? $t('m.Remove')
                          : $t('m.Invite_merchant_owner')
                      }}</el-dropdown-item
                    >
                    <el-dropdown-item
                      @click.native="shopOperationState(scope.row)"
                      v-if="scope.row.state == 3 && permissionsLists(206)"
                      >{{ $t('m.Start_operations') }}</el-dropdown-item
                    >
                    <el-dropdown-item
                      @click.native="shopRule(scope.row)"
                      v-if="permissionsLists(174)"
                      >{{ $t('m.settingPricePlan') }}</el-dropdown-item
                    >
                  </el-dropdown-menu>
                </el-dropdown>
              </template>
            </el-table-column>
            <emptydata
              slot="empty"
              v-if="!page.records || page.records.length == 0"
            />
          </el-table>
          <el-pagination
            background
            :page-sizes="[10, 20, 30, 40, 50]"
            :page-size="page.size"
            :current-page.sync="page.current"
            layout="total, sizes, prev, pager, next, jumper"
            :pager-count="5"
            :total="page.total"
            class="el_pagination"
            @size-change="changePageSize"
            @current-change="changePageNum"
            v-show="page.total > 0"
          >
          </el-pagination>
        </div>
      </div>

      <!-- 恢复合作/停止合作 -->
      <el-dialog
        :close-on-click-modal="false"
        :visible.sync="cooperationDialog"
        :title="
          shopRow.state == 2
            ? $t('m.branch_resumePartnership')
            : $t('m.branch_Terminate')
        "
        width="520px"
        top="200px"
        append-to-body
      >
        <div class="dialog_content">
          <div class="dialog_content1">
            {{
              shopRow.state == 2
                ? $t('m.Confirm_reactivate_shop')
                : $t('m.Confirm_terminate')
            }}
          </div>
          <div class="dialog_content2">
            <img src="@/assets/imgs/ic_warn.svg" alt="" class="dialog_warn" />
            {{
              shopRow.state == 2
                ? $t('m.Profit_to_merchant')
                : $t('m.No_profit_to_merchant')
            }}
          </div>
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button @click="cooperationDialog = false" class="cancel_btn">{{
            $t('m.cancel')
          }}</el-button>
          <el-button @click="changeState" class="cancel_btn confirm_btn">{{
            $t('m.confirm_')
          }}</el-button>
        </span>
      </el-dialog>

      <!-- 计费规则 -->
      <el-dialog
        :close-on-click-modal="false"
        :visible.sync="ruleDialog"
        :title="$t('m.settingPricePlan')"
        width="520px"
        top="200px"
        append-to-body
      >
        <div class="dialog_content">
          <div class="dialog_content1">
            {{ $t('m.Franchisee_belong') }}:
            {{ shopRow.agentName ? shopRow.agentName : $t('m.Platform') }}
          </div>
          <div class="dialog_content1">
            {{ $t('m.settingSetUpRentalOrderPricePlan') }}:
          </div>

          <div class="dialog_content3">
            <el-form
              style="width:100%"
              :model="ruleForms"
              :rules="rules"
              ref="ruleForms"
            >
              <el-form-item prop="billingId">
                <el-select
                  v-model="ruleForms.billingId"
                  :placeholder="$t('m.Select_Pricing_Plan')"
                  style="width:100%"
                  filterable
                >
                  <el-option
                    v-for="item in billingOptions"
                    v-show="!item.isSystem"
                    :disabled="item.isSystem"
                    :key="item.id"
                    :label="item.title"
                    :value="item.id"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </el-form>
          </div>
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button @click="ruleDialog = false" class="cancel_btn">{{
            $t('m.cancel')
          }}</el-button>
          <el-button @click="editRule" class="cancel_btn confirm_btn">{{
            $t('m.confirm_')
          }}</el-button>
        </span>
      </el-dialog>

      <!-- 邀请店主 / 解除绑定 -->
      <el-dialog
        :close-on-click-modal="false"
        :visible.sync="inviteDialog"
        :title="linkType == 1 ? $t('m.Invite_merchant_owner') : $t('m.Remove')"
        width="520px"
        top="200px"
        append-to-body
      >
        <div class="dialog_content el_input_disabled" v-if="linkType == 1">
          <div class="dialog_content1">
            {{ $t('m.Choose_oneWay_invite_merchant') }}
          </div>
          <el-radio-group v-model="elRadio" style="margin-bottom:12px;">
            <el-radio :label="1">{{
              $t('m.Invite_by_Invitation_link')
            }}</el-radio>
            <el-radio :label="2">{{ $t('m.Invite_by_email') }}</el-radio>
          </el-radio-group>
          <div class="dialog_content3">
            <el-input
              v-show="elRadio == 1"
              style="width:100%;"
              disabled
              :value="inviteData.inviteUrl"
              ><template slot="append"
                ><div @click="$util.copyText(inviteData.inviteUrl)">
                  {{ $t('m.Copy') }}
                </div></template
              ></el-input
            >
            <el-form
              style="width:100%"
              v-if="elRadio == 2"
              :model="ruleForm"
              :rules="rules"
              ref="ruleForm"
            >
              <el-form-item prop="email" key="email">
                <el-input
                  v-model="ruleForm.email"
                  maxlength="320"
                  style="width:100%;"
                  :placeholder="$t('m.Please_enter')"
                  clearable
                ></el-input>
              </el-form-item>
            </el-form>
          </div>
          <div
            class="dialog_content2"
            v-show="elRadio == 1"
            style="margin-top:12px;"
          >
            {{
              $t('m.Expire_in_fourteen')
                .replace('$times', inviteData.remainDays)
                .replace(
                  '$days',
                  inviteData.remainDays > 1 ? $t('m.days') : $t('m.day')
                )
            }}
          </div>
        </div>
        <div class="dialog_content" v-else>
          <div class="dialog_content1">
            {{ $t('m.After_removing_merchant') }}
          </div>
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button
            class="cancel_btn"
            v-if="linkType == 2"
            @click="inviteDialog = false"
            >{{ $t('m.cancel') }}</el-button
          >
          <el-button @click="submitInvite" class="cancel_btn confirm_btn">{{
            $t('m.confirm_')
          }}</el-button>
        </span>
      </el-dialog>

      <!-- 商家开始运营-->
      <el-dialog
        :close-on-click-modal="false"
        :visible.sync="operationDialog"
        :title="$t('m.Start_operations')"
        width="520px"
        top="200px"
        append-to-body
      >
        <div class="dialog_content">
          <div class="dialog_content1">
            {{ $t('m.Start_operations_tip') }}
          </div>
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button @click="operationDialog = false" class="cancel_btn">{{
            $t('m.cancel')
          }}</el-button>
          <el-button @click="sumbitOperation" class="cancel_btn confirm_btn">{{
            $t('m.confirm_')
          }}</el-button>
        </span>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import page from '@/mixins/page'
export default {
  mixins: [page],
  data () {
    return {
      datePickerOptions: {
        disabledDate (time) {
          let current_time = new Date().Format('yyyy-MM-dd') + ' 23:59:59' //时间日期为: ‘当前日期 23:59:59’
          let t = new Date(current_time).getTime() //‘当前日期 23:59:59’的时间戳
          return time.getTime() > t
        }
      },
      params: {
        agentId: '', //代理id
        search: '', //模糊查询
        rangeTime: '', //时间戳范围
        state: '', //状态:0-待激活 1-正常 2-停止合作
        industryId: '' //商铺类型
      },
      typeOption: [
        {
          id: '',
          description: '',
          industryName: this.$t('m.all')
        }
      ],
      stateOption: [
        {
          value: '',
          label: this.$t('m.all')
        },
        {
          value: 1,
          label: this.$t('m.Normal_cooperation')
        },
        {
          value: 2,
          label: this.$t('m.Terminate')
        },
        {
          value: 0,
          label: this.$t('m.agency_activated')
        },
        {
          value: 3,
          label: this.$t('m.BrandState1')
        }
      ],

      cooperationDialog: false, //合作弹窗
      ruleDialog: false, //计费规则弹窗
      ruleForms: {
        billingId: ''
      },
      rules: {
        email: [
          {
            required: true,
            message: this.$t('m.Enter_invitation_email'),
            trigger: 'blur'
          },
          {
            pattern: this.$reg.email.val,
            message: this.$t('m.EnterCorrectEmail'),
            trigger: 'blur'
          }
        ],
        billingId: [
          {
            required: true,
            message: this.$t('m.Select_Pricing_Plan'),
            trigger: 'change'
          }
        ]
      },
      billingOptions: [], //计费规则
      shopRow: '', //选中店铺

      ruleForm: {
        email: ''
      },
      elRadio: 1, // 邀请类型
      inviteDialog: false, //邀请链接弹窗
      linkType: 1, //邀请链接弹窗类型
      inviteData: '', //邀请链接及时间
      operationDialog: false, //商家运营
      permissionsIds: [],
      userType: this.getUserType() //用户类型
    }
  },
  created () {
    this.$store.state.permissions.forEach(item => {
      this.permissionsIds.push(Number(this.$jsencrypt.decrypt(item)))
    })
    if (!this.permissionsLists(19)) {
      return
    }
    this.timeDefaultShow = new Date()
    this.timeDefaultShow.setMonth(new Date().getMonth() - 1)
    this.getShopLists()
    this.getIndustrys()
  },
  mounted () {},
  methods: {
    //权限id校验
    permissionsLists (val) {
      return this.permissionsIds.includes(val)
    },
    //获取行业列表
    getIndustrys () {
      this.$api.common.getIndustriesList().then(res => {
        if (this.$ok(res)) {
          let array = res.data.map(item => {
            item.industryName = this.$format.langFormat(
              item.industryName,
              this.$cache.getLang()
            )
            item.description = this.$format.langFormat(
              item.description,
              this.$cache.getLang()
            )
            return item
          })
          this.typeOption = this.typeOption.concat(array)
          // console.log(this.typeOption)
        }
      })
    },

    //获取店铺列表
    getShopLists () {
      this.$api.shop.getShopList(this.params, this.page).then(res => {
        if (this.$ok(res)) {
          this.page = res.data
        }
      })
    },
    // 搜索/重置
    searchClick (reset, e) {
      // 是否重置
      let size = this.page.size
      this.page = this.$options.data.call(this).page
      if (reset) {
        this.params = this.$options.data.call(this).params
        this.timeDefaultShow = new Date()
        this.timeDefaultShow.setMonth(new Date().getMonth() - 1)
        this.remPageNum()
      } else {
        this.page.size = size
        this.setPageNum(this.page.current, this.page.size, this.params)
      }
      this.$nextTick(() => {
        e ? this.$refs[`select${e}`].blur() : ''
      })
      this.getShopLists()
    },
    // 每页数
    changePageSize (val) {
      this.page.current = 1
      this.page.size = val
      this.getShopLists()
    },
    // 当前页
    changePageNum (val) {
      this.page.current = val
      this.getShopLists()
    },
    //详情
    detailClick (id) {
      this.setPageNum(this.page.current, this.page.size, this.params)
      this.$router.push({ path: '/vender/shop/detail', query: { id: id } })
    },
    //编辑商家
    eidtShop (id) {
      this.setPageNum(this.page.current, this.page.size, this.params)
      this.$router.push({
        path: '/vender/shop/create',
        query: {
          id: id,
        }
      })
    },
    //打开计费规则
    shopRule (item) {
      this.shopRow = item
      this.ruleForms.billingId = item.billingId || ''
      this.getRule(item)
    },
    //计费规则
    getRule (item) {
      let params = {
        agentId: item.agentId
      }
      this.$api.setting
        .getBillingOption(item.agentId ? params : '')
        .then(res => {
          if (this.$ok(res)) {
            this.billingOptions = res.data
            this.ruleDialog = true
          }
        })
    },
    //修改计费规则
    editRule () {
      this.$refs.ruleForms.validate(valid => {
        if (valid) {
          this.$api.setting
            .editRules(this.shopRow.id, this.ruleForms.billingId)
            .then(res => {
              if (this.$ok(res)) {
                this.$message.success(res.message)
                this.ruleDialog = false
                this.getShopLists()
              } else {
                this.$message.error(res.message)
              }
            })
        }
      })
    },
    // 打开邀请/解绑弹窗
    inviteStore (item) {
      this.shopRow = item
      if (item.uid) {
        this.linkType = 2
        this.inviteDialog = true
      } else {
        this.inviteShopkeeper(item.id)
      }
    },
    //邀请店主
    inviteShopkeeper (id) {
      this.$api.branch.inviteShopkeeper(id).then(res => {
        if (this.$ok(res)) {
          this.inviteDialog = true
          this.inviteData = res.data
          this.elRadio = 1
          this.linkType = 1
          this.ruleForm.email = ''
        } else {
          this.$message.error(res.message)
        }
      })
    },

    //邀请店主-邮件
    inviteShopemail () {
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          this.$api.branch
            .inviteShopemail(this.shopRow.id, this.ruleForm)
            .then(res => {
              if (this.$ok(res)) {
                this.$message.success(res.message)
                this.inviteDialog = false
              } else {
                this.$message.error(res.message)
              }
            })
        }
      })
    },
    //解绑店主
    unbindShopkeeper () {
      this.$api.branch.unbindShopkeeper(this.shopRow.id).then(res => {
        if (this.$ok(res)) {
          this.inviteDialog = false
          this.$message.success(res.message)
          this.getShopLists()
        } else {
          this.$message.error(res.message)
        }
      })
    },
    //确认邀请/解绑
    submitInvite () {
      if (this.linkType == 2) {
        this.unbindShopkeeper()
      } else {
        this.elRadio == 1 ? (this.inviteDialog = false) : this.inviteShopemail()
      }
    },
    //合作弹窗
    dialogClick (item) {
      this.shopRow = item
      this.cooperationDialog = true
    },
    //修改店铺状态
    changeState () {
      let params = {
        id: this.shopRow.id,
        state: this.shopRow.state == 1 ? 2 : 1,
        isRecoveries: false
      }
      this.$openLoading()
      this.$api.shop.shopState(params).then(res => {
        if (this.$ok(res)) {
          this.$message.success(res.message)
          this.getShopLists()
          this.cooperationDialog = false
          this.$closeLoading()
        } else {
          this.$message.error(res.message)
          this.$closeLoading()
        }
      })
    },

    //打开运营确认弹窗
    shopOperationState (item) {
      this.shopRow = item
      this.operationDialog = true
    },

    //确认运营
    sumbitOperation () {
      this.$api.branch.editOperationState(this.shopRow.id).then(res => {
        if (this.$ok(res)) {
          this.operationDialog = false
          this.$message.success(res.message)
          this.getShopLists()
        } else {
          this.$message.error(res.message)
        }
      })
    }
  }
}
</script>
